//
//  UserInfoManager.m
//  MinesTime
//
//  Created by imac on 2017/10/30.
//  Copyright © 2017年 MS1968. All rights reserved.
//

#import "UserInfoManager.h"
#import "MeRegisterVC.h"
#import <objc/runtime.h>
#import "MyEnquiryListModel.h"
#import "SSGAFSimpleTool.h"


@interface UserInfoManager ()
//@property (nonatomic, copy) LoginSuccessBlock loginSuccessBlock;
@property (nonatomic,assign)BOOL type;
@end
@implementation UserInfoManager

+ (instancetype)defaultManager {
    
    static UserInfoManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[UserInfoManager alloc] init];
        
    });
    return manager;
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {}

- (NSString *)description {
    
    return [self yy_modelDescription];
}


- (instancetype)init {
    
    if (self = [super init]) {
        if ([self getUserInfoByLibrary]) {
            [self setUserInfoWithModel:[self getUserInfoByLibrary]];
        }
    }
    return self;
}



//- (NSString *)mobile {
//    if (self.userName) {
//        NSMutableString *replaceMobile = [[NSMutableString alloc] initWithString:self.userName];
//        [replaceMobile replaceCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
//        return replaceMobile;
//    }
//    if (_mobile) {
//        return _mobile;
//    }
//    return @"";
//}

// 用户是否登录
- (BOOL)userIsLogin {
    
    if (self.userId && self.token &&self.userId.length>0) {
        return YES;
    } 
    return NO;
}
// 登录成功后回调
//- (void)loginSuccessCallback {
//    if (self.loginSuccessBlock) {
//        self.loginSuccessBlock();
//    }
//}
- (void)loginInterceptorWithParentVC:(UIViewController *)vc LoggedBlock:(LoggedBlock)loggedBlock loginSuccessBlock:(LoginSuccessBlock)loginSuccessBlock {
    if ([self userIsLogin]) {
        if (loggedBlock) {
            loggedBlock();
        }
    } else {
        // 未登录跳转到登录, 登录后回调
//        self.loginSuccessBlock = loginSuccessBlock;
        
        MeRegisterVC *loginVC = (MeRegisterVC *)[[UIStoryboard storyboardWithName:@"LoginVC" bundle:nil] instantiateViewControllerWithIdentifier:@"LoginVC"];
        
//        loginVC.isLoginBlock = ^(BOOL isLogin) {
//            if (isLogin == YES) {
//                if (loginSuccessBlock) {
//                    loginSuccessBlock();
//                }
//            }
//        };
        
        [vc presentViewController:[[UINavigationController alloc] initWithRootViewController:loginVC] animated:YES completion:nil];
    }
}

// 设置信息
- (void)setUserInfoWithModel:(UserInfoManager *)model {
    
    /** 用户设备 ID */
    self.device= model.device;
    /**  用户手机号 */
    self.phone= model.phone;
    /** 用户ID */
    self.userId= model.userId;
    /** 上次用户数据更新时间 */
    self.updateTime= model.updateTime;
    /** 上次登录时间 */
    self.loginTime= model.loginTime;
    /** 用户token */
    self.token= model.token;
    /** 用户注册时间 */
    self.createTime= model.createTime;
    /** 用户头像 */
    self.avatar= model.avatar;
    /** 用户名称 */
    self.nickName= model.nickName;
    /** 邮箱 */
    self.email= model.email;

    
    
    self.getMyEnquiryList= model.getMyEnquiryList;
    self.getFollowGoods= model.getFollowGoods;
    
    self.refresh = model.refresh;
    
    self.arrMUgcReleaseFailure = model.arrMUgcReleaseFailure;
    self.isPublish = model.isPublish;
    
    self.isSTViewControllerRefresh = model.isSTViewControllerRefresh;
    self.isSTViewController = model.isSTViewController;
    [self saveUserInfoToLibrary:model];
    // ssgaf同步登入token
  //  [[SSGAFSimpleTool sharedManager]updateToken];
}

// 设置信息
- (void)setUserInfoWithNSDictionary:(NSDictionary *)div {
    
    /** 用户设备 ID */
    self.device= div[@"device"];
    /**  用户手机号 */
    self.phone= div[@"phone"];
    /** 用户ID */
    self.userId= div[@"userId"];
    /** 上次用户数据更新时间 */
    self.updateTime=  div[@"updateTime"];
    /** 上次登录时间 */
    self.loginTime= div[@"loginTime"];
    /** 用户token */
    self.token= div[@"token"];
    /** 用户注册时间 */
    self.createTime= div[@"createTime"];
    /** 用户头像 */
    self.avatar=  div[@"avatar"];
    /** 用户名称 */
    self.nickName= div[@"nickName"];
    self.email= div[@"email"];

}
// 保存到沙盒
- (void)saveUserInfoToLibrary:(UserInfoManager *)model {
    NSData *modelData = [NSKeyedArchiver archivedDataWithRootObject:model];
    [kUSER_DEFAULTS setObject:modelData forKey:kUSER_INFO];
    [kUSER_DEFAULTS synchronize];
}

// 从沙盒获取用户信息
- (UserInfoManager *)getUserInfoByLibrary {
    NSData *modelData = [kUSER_DEFAULTS objectForKey:kUSER_INFO];
    [kUSER_DEFAULTS synchronize];
    UserInfoManager *userInfo = [NSKeyedUnarchiver unarchiveObjectWithData:modelData];
    
    return userInfo;
}

// 删除用户信息
- (void)removeUserInfo {
    [kUSER_DEFAULTS removeObjectForKey:kUSER_INFO];
    [kUSER_DEFAULTS synchronize];
    [self setUserInfoWithModel:nil];
//    dispatch_async(dispatch_get_main_queue(), ^{
//     
//    });
    
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [self yy_modelEncodeWithCoder:aCoder];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    return [self yy_modelInitWithCoder:aDecoder];
}

/**更新列表显示*/
- (void) MyList{
    self.type = NO;
    
    if (![self userIsLogin]) {
        kUSER_INFO_MANAGER.getFollowGoods = NO;
        kUSER_INFO_MANAGER.getMyEnquiryList = NO;
        return;
    }
    kUSER_INFO_MANAGER.getMyEnquiryList = NO;

    //询价历史记录
//    [[serviceDefualt loadgetMyEnquiryList:nil]subscribeNext:^(ResponseData *x) {
//        if (x.success) {
////            MyEnquiryListModel *model = [MyEnquiryListModel yy_modelWithJSON:x.responseRawData];
//            NSArray *arr = x.responseRawData[@"data"];
//
//            if (arr.count==0&&!self.type) {
//                if (kUSER_INFO_MANAGER.getMyEnquiryList != NO) {
//                    kUSER_INFO_MANAGER.getMyEnquiryList = NO;
//                }
//            } else {
//                self.type = YES;
//                if (kUSER_INFO_MANAGER.getMyEnquiryList != YES) {
//                    kUSER_INFO_MANAGER.getMyEnquiryList = YES;
//                }
//            }
//        }else{
//            if (!self.type) {
//                kUSER_INFO_MANAGER.getMyEnquiryList = NO;
//            }
//        }
//    }];
    
    //已结束询价
//    [[serviceDefualt loadgetMyEndEnquiryList:0 reponseObjctClass:[MyEnquiryListModel class]]subscribeNext:^(ResponseData *  x) {
//        if (x.success) {
//            
//            NSArray *arr = x.responseRawData[@"data"];
//            
//            if (arr.count==0&&!self.type) {
//                if (kUSER_INFO_MANAGER.getMyEnquiryList != NO) {
//                    kUSER_INFO_MANAGER.getMyEnquiryList = NO;
//                }
//                
//            } else {
//                self.type = YES;
//                if (kUSER_INFO_MANAGER.getMyEnquiryList != YES) {
//                    kUSER_INFO_MANAGER.getMyEnquiryList = YES;
//                }
//                
//            }
//            
//        }else{
//            if (!self.type) {
//            kUSER_INFO_MANAGER.getMyEnquiryList = NO;
//            }
//        }
//    }
//     ];
    
    //关注
    [[serviceDefualt loadgetFollowGoodspage:0 reponseObjctClass:nil]subscribeNext:^(ResponseData *x) {
        if (x.success) {
            
            NSArray *arr = x.responseRawData[@"data"];
            
            if (arr.count==0) {
                if (  kUSER_INFO_MANAGER.getFollowGoods != NO) {
                    kUSER_INFO_MANAGER.getFollowGoods = NO;
                }
            } else {
                kUSER_INFO_MANAGER.getFollowGoods = YES;
                
                if (  kUSER_INFO_MANAGER.getFollowGoods != YES) {
                    kUSER_INFO_MANAGER.getFollowGoods = YES;
                }
                
            }
            
        }else{
            kUSER_INFO_MANAGER.getFollowGoods = NO;
        }
        
    }];

}



//Save Cookie
-(void)saveCookie{
    /**
     *先判断是否有 相同 Cookie
     *
     *
     **/
    
    NSUserDefaults*userDefaults = [NSUserDefaults standardUserDefaults];
    
    //对取出的cookie进行反归档处理
    
    NSArray * cookies1 = [NSKeyedUnarchiver unarchiveObjectWithData:[userDefaults objectForKey:@"Cookie"]];
    
    NSMutableArray *ArrM = [[NSMutableArray alloc]initWithArray:cookies1];
    
    //获取cookie
    
    NSArray*cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    
    for (id obj in cookies) {
        if (![ArrM containsObject:obj]) {
            [ArrM addObject:obj];
        }else{
            
        }
    }
    
    //把cookie进行归档并转换为NSData类型
    
    [ArrM addObjectsFromArray:cookies];
    
    NSData*cookiesData = [NSKeyedArchiver archivedDataWithRootObject:cookies];
    
    //存储归档后的cookie
    
    [userDefaults setObject: cookiesData forKey:@"cookie"];
    
}

//set Cookie
-(void)setCookie{
    //取出保存的cookie
    
    NSUserDefaults*userDefaults = [NSUserDefaults standardUserDefaults];
    
    //对取出的cookie进行反归档处理
    
    NSArray*cookies = [NSKeyedUnarchiver unarchiveObjectWithData:[userDefaults objectForKey:@"cookie"]];
    
    if(cookies) {
        
        //设置cookie
        
        NSHTTPCookieStorage*cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        
        for(id cookie in cookies) {
            
            [cookieStorage setCookie:(NSHTTPCookie*)cookie];
            
        }
        
//        return YES;
    }
    
//    return NO;
}

-(void)cleanCookie {
    
    NSUserDefaults*userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults removeObjectForKey:@"cookie"];
//    [self setCookie];
}

/** 添加一条失败发表记录 */
-(void)addFailureModel:(UgcReleaseFailureModel*)modelSon{
    UserInfoManager *model = kUSER_INFO_MANAGER;
    if (!model.arrMUgcReleaseFailure) {
        model.arrMUgcReleaseFailure = [[NSMutableArray alloc]init];
    }
    [model.arrMUgcReleaseFailure addObject:modelSon];
    [model setUserInfoWithModel:model];
}

/** 删除一条失败发表记录 */
-(void)delFailureModel:(NSInteger)index{
    UserInfoManager *model = kUSER_INFO_MANAGER;
    if (!model.arrMUgcReleaseFailure) {
        model.arrMUgcReleaseFailure = [[NSMutableArray alloc]init];
    }
    [model.arrMUgcReleaseFailure removeObjectAtIndex:model.arrMUgcReleaseFailure.count-1-index];
    [model setUserInfoWithModel:model];
}

- (void)saveUserInfoSelf{
    [self saveUserInfoToLibrary:self];
}
@end

//// -----------------------------------------------------
//@implementation UserInfoModel
//
//- (NSString *)description {
//    return [self yy_modelDescription];
//}
//
//+ (NSDictionary *)modelContainerPropertyGenericClass {
//    return @{@"userInfo": [UserInfoManager class]};
//}
//
//@end
